<template>
  <div ref="table" class="custom-table-wrap">
    <a-table
      ref="a-table"
      :loading="loading"
      :scroll="scrollOpt"
      :pagination="pagination"
      :selection="selection"
      :columns="columns"
      :data-source="tableData"
      :rowSelection="rowSelection === null ? rowSelection : rowSelections"
      @change="handlerChange"
    >
      <template
        v-for="item in slotOpt"
        :slot="item.slot"
        slot-scope="text, scope, index"
      >
        <span :key="item.slot">
          <component
            v-on="$listeners"
            :is="item.component"
            :instance="item"
            :scope="{ text, scope, index, customPaginationOpt }"
          >
          </component>
        </span>
      </template>
    </a-table>
  </div>
</template>

<script>
import { baseTableSlot } from './configs/config'
import Action from './components/action.vue'
import CompanyInfo from './components/companyInfo.vue'
import Color from './components/color.vue'
import Subscript from './components/subscript.vue'
import TextAction from './components/common/textAction.vue'
import CompetitorStatus from './components/common/competitorStatus.vue'
import MultipleRadio from './components/common/multipleRadio.vue'
import Graphical from './components/graphical.vue'
import Brief from './components/common/brief.vue'

export default {
  props: {
    customPaginationOpt: Object, // 自定义分页器的时候如果需要计算序号，需要把参数传进来
    customSlotOpt: Array, // table的插槽配置文件
    options: Array, // 表格配置
    tableValue: Array, // 表格值
    otherOpt: Object, // 分页器的配置文件
    rowSelection: {
      // 按需是否显示选择按钮框,传入null即可不显示选择框，不传则默认显示
      type: Object,
      default: () => {}
    }
  },
  components: {
    // 下标
    Action,
    Color,
    Subscript,
    // 业务插槽
    TextAction,
    CompetitorStatus,
    MultipleRadio,
    Graphical,
    CompanyInfo,
    Brief
  },
  data() {
    return {
      loading: false,
      baseTableSlot, // 默认的插槽配置
      pagination: {
        // 分页器配置
        total: 0,
        current: 1,
        pageSize: 10,
        pageNum: 1,
        defaultPageSize: 10, // 默认10条
        showSizeChanger: false // 禁用改变pageSize
      },
      selection: {}, // 自定义选择配置项
      slotOpt: [], // 合并自定义与默认表格的插槽配置
      selectedRowIds: [], // 已选的row的id
      tableData: [], // 表格结果
      columns: [], // 表格配置
      scrollOpt: { y: 240 } // 滚动条配置
    }
  },
  mounted() {
    this.initSetting()
    // this.$nextTick(() => {
    //   this.$once('hook:updated', this.updateScrollOpt)
    // })
    // window.onLoad = this.updateScrollOpt() // 视窗更新的时候，也重新设置滚动条的宽高
  },
  computed: {
    rowSelections() {
      const { selectedRowIds } = this
      return {
        selectedRowIds,
        onChange: this.onSelected
      }
    }
  },
  watch: {
    tableValue: {
      handler(newVal) {
        if (newVal) {
          this.normalizeRowData(newVal) // 规范化结果
        }
      },
      immediate: true,
      deep: true
    },
    otherOpt: {
      handler() {
        this.normalizePaginationOpt()
      },
      deep: true
    }
  },
  methods: {
    // 初始化分页器
    initPagination() {
      this.normalizePaginationOpt()
    },
    // 分页器，全选等变化监听
    handlerChange(params) {
      this.pagination.pageNum = params.current
      this.pagination.current = params.current
      this.selectedRowIds = [] // 分页器变化的时候，清空勾选
      this.$emit('change', { ...arguments })
    },
    // 处理当前选中的结果
    onSelected(item, rowKeys) {
      this.selectedRowIds = rowKeys.map(item => item)
    },
    initSetting() {
      this.setSlotOpt() // 初始化插槽配置
      this.normalizeFields() // 规范化fields的每一项配置
      this.normalizePaginationOpt() // 统一融合剩余配置
    },
    // 统一融合剩余配置
    normalizePaginationOpt() {
      if (!this.otherOpt) return
      Object.keys(this.otherOpt).forEach(key => {
        const t = this.otherOpt[key]
        if (key === 'pagination' && t === false) {
          this[key] = t
        } else if (this[key]) {
          Object.assign(this[key], t)
        }
      })
    },
    // 规范化fields的每一项配置
    normalizeFields() {
      this.columns = this.options.reduce((pre, cur) => {
        if (!cur.width) cur.width = 150 // 默认column的宽度
        pre.push(cur)
        return pre
      }, [])
    },
    // 初始化插槽配置
    setSlotOpt() {
      const resultOpt = [].concat(this.baseTableSlot) // 最终结果配置
      if (this.customSlotOpt) {
        this.customSlotOpt.forEach(item => {
          const includeIndex = resultOpt.findIndex(t => t.slot === item.slot) // 存在
          if (includeIndex !== -1) {
            // 根据下标替换
            resultOpt.splice(includeIndex, 1, item)
          } else {
            resultOpt.push(item)
          }
        })
      }
      this.slotOpt = resultOpt
    },
    // 规范化表格结果
    normalizeRowData(val) {
      this.tableData = val.reduce((pre, cur, index) => {
        if (!cur.key) {
          const tamp = Date.parse(new Date()) // 获取时间戳
          cur.key = `${index}_${tamp}`
        }
        pre.push(cur)
        return pre
      }, [])
    },
    // 修改表格的加载状态
    settingLoading(v) {
      this.loading = v
    },
    //
    // 更新表格滚动条的计算
    // updateScrollOpt() {
    //   // 表格内容距离容器顶部的距离
    //   const tHeader = document.getElementsByClassName('ant-table-thead')[0]
    //   let paginationHeight = 28 // 写死一个默认值先

    //   if (document.getElementsByClassName('ant-pagination')[0]) {
    //     paginationHeight = document.getElementsByClassName('ant-pagination')[0]
    //       .offsetHeight
    //   }
    //   const footerHeight = document.getElementsByClassName(
    //     'home-footer-warp'
    //   )[0].offsetHeight
    //   let tHeaderBottom = 0
    //   if (tHeader) {
    //     tHeaderBottom = tHeader.getBoundingClientRect().bottom
    //   }
    //   const height = `calc(100vh - ${paginationHeight * 2 +
    //     footerHeight +
    //     tHeaderBottom}px)`
    //     console.log(height,'height');
    //   this.scrollOpt.y = height < 200 ? 450 : height
    //   this.scrollOpt.x = '100%'
    // }
  }
}
</script>
